#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <modbus/modbus.h>
#include "modbus_client.h"
#include "common.h"

// 生成随机寄存器数据
void generate_random_registers(uint16_t* registers, uint32_t count) {
    for (uint32_t i = 0; i < count; i++) {
        registers[i] = (uint16_t)(rand() % 65536);
    }
}

// 执行压力测试
int execute_pressure_test(modbus_client_t* client) {
    // 准备寄存器数据
    uint16_t write_registers[REGISTER_COUNT];
    uint16_t read_registers[REGISTER_COUNT];
    
    uint32_t holding_start = client->config.holding_register_range.start_address;
    uint32_t holding_end = client->config.holding_register_range.end_address;
    
    if (holding_end - holding_start < REGISTER_COUNT) {
        fprintf(stderr, "Error: Holding register range too small for %d registers\n", REGISTER_COUNT);
        return -1;
    }
    
    srand((unsigned int)time(NULL));

    uint64_t test_duration_ns = 
        client->config.test_duration.duration_hours * 3600ULL * NS_PER_SEC +
        client->config.test_duration.duration_minutes * 60ULL * NS_PER_SEC +
        client->config.test_duration.duration_seconds * NS_PER_SEC;
    
    uint64_t start_time = get_monotonic_time_ns();
    uint64_t end_time = start_time + test_duration_ns;
    
    printf("1ms固定周期压力测试开始，将持续 %u 小时 %u 分钟 %u 秒\n",
           client->config.test_duration.duration_hours,
           client->config.test_duration.duration_minutes,
           client->config.test_duration.duration_seconds);
    
    // 初始化周期统计
    init_cycle_stats(&client->timing_stats);
    
    // 状态跟踪
    bool response_received = true;
    uint64_t last_send_time = 0;
    int64_t response_time = 0; // 在函数作用域内定义
    
    const uint32_t IGNORE_INITIAL_OPS = 2;
    uint32_t valid_ops_started = 0;
    
    // 固定1ms周期
    init_periodic_timer(&client->timer, 1000000ULL); // 1ms
    
    while (client->running && get_monotonic_time_ns() < end_time) {
        uint64_t cycle_start = get_monotonic_time_ns();
        
        // 更新周期统计
        if (client->total_operations > 0) {
            int64_t actual_cycle_time = cycle_start - client->timer.last_operation_start;
            update_cycle_stats(&client->timing_stats, actual_cycle_time);
        }
        
        // 如果上个周期收到响应，这个周期发送新报文
        if (response_received) {
            client->total_operations++;
            
            // 记录发送时间
            last_send_time = get_monotonic_time_ns();
            
            // 随机选择功能码
            modbus_function_t function = (rand() % 2 == 0) ? 
                FUNCTION_READ_HOLDING_REGISTERS : FUNCTION_WRITE_HOLDING_REGISTERS;
            
            int result = -1;
            uint32_t address = holding_start + (rand() % (holding_end - holding_start - REGISTER_COUNT + 1));
            
            switch (function) {
                case FUNCTION_WRITE_HOLDING_REGISTERS:
                    generate_random_registers(write_registers, REGISTER_COUNT);
                    result = modbus_write_registers(client->ctx, address, REGISTER_COUNT, write_registers);
                    break;
                    
                case FUNCTION_READ_HOLDING_REGISTERS:
                    result = modbus_read_registers(client->ctx, address, REGISTER_COUNT, read_registers);
                    break;
            }
            
            uint64_t op_end = get_monotonic_time_ns();
            response_time = op_end - last_send_time; // 计算响应时间
            
            // 更新最大响应时间
            if (response_time > 0) {
                uint64_t response_time_uint = (uint64_t)response_time;
                if (response_time_uint > client->timer.max_response_ns) {
                    client->timer.max_response_ns = response_time_uint;
                }
            }
            
            if (result == REGISTER_COUNT) {
                client->successful_operations++;
                response_received = true;
                client->timing_stats.response_analysis.cycles_with_response++;
                client->timing_stats.response_analysis.current_consecutive_misses = 0;
            } else {
                response_received = false;
                client->timing_stats.response_analysis.current_consecutive_misses++;
                
                if (client->timing_stats.response_analysis.current_consecutive_misses > 
                    client->timing_stats.response_analysis.max_consecutive_misses) {
                    client->timing_stats.response_analysis.max_consecutive_misses = 
                        client->timing_stats.response_analysis.current_consecutive_misses;
                }
                
                if (errno == ETIMEDOUT) {
                    client->timeout_errors++;
                } else {
                    client->other_errors++;
                }
            }
        } else {
            // 上个周期没收到响应，这个周期继续等待
            response_time = 0; // 无响应时响应时间为0
        }
        
        // 更新总周期数
        client->timing_stats.response_analysis.total_cycles++;
        
        // 计算时间统计
        int64_t interval_time = (client->total_operations > 0) ? 
            (cycle_start - client->timer.last_operation_start) : client->timer.period_ns;
        
        int64_t interval_jitter = (client->total_operations > 0) ? 
            (cycle_start - (client->timer.last_operation_start + client->timer.period_ns)) : 0;
        
        // 更新统计
        if (valid_ops_started >= IGNORE_INITIAL_OPS) {
            update_timing_stats(&client->timing_stats, 
                              response_time, // 使用计算好的响应时间
                              interval_time,
                              interval_jitter,
                              false);
        } else {
            valid_ops_started++;
        }
        
        client->timer.last_operation_start = cycle_start;
        
        // // 定期输出统计
        // if (client->total_operations % 10000 == 0) {
        //     printf("Op %lu: %s (resp: %.3fms, max resp: %.3fms)\n", 
        //            client->total_operations,
        //            response_received ? "响应" : "无响应",
        //            response_time / 1000000.0,
        //            client->timer.max_response_ns / 1000000.0);
        // }
        
        // 等待下一个周期
        wait_next_period(&client->timer);
    }
    
    // 打印最终统计
    printf("\n=== 1ms固定周期压力测试最终统计 ===\n");
    printf("总操作数: %lu\n", client->total_operations);
    printf("成功操作数: %lu (%.1f%%)\n", 
           client->successful_operations,
           (double)client->successful_operations / client->total_operations * 100);
    printf("总周期数: %lu\n", client->timing_stats.response_analysis.total_cycles);
    printf("有响应周期数: %lu (%.1f%%)\n",
           client->timing_stats.response_analysis.cycles_with_response,
           (double)client->timing_stats.response_analysis.cycles_with_response / 
           client->timing_stats.response_analysis.total_cycles * 100);
    printf("最大连续无响应周期数: %lu\n",
           client->timing_stats.response_analysis.max_consecutive_misses);
    printf("最大响应时间: %.3f ms\n", client->timer.max_response_ns / 1000000.0);
    
    // 响应耗时占比分析
    double response_ratio = calculate_response_time_ratio(&client->timing_stats);
    printf("响应耗时占比: %.3f%%\n", response_ratio * 100);
    
    // 时钟精度验证
    print_cycle_stats(&client->timing_stats);
    
    // 原有统计
    print_timing_stats(&client->timing_stats, client->timer.period_ns);
    
    return 0;
}